package com.bocloud.kong.service.impl;

import static org.apache.commons.lang3.StringUtils.isBlank;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.bocloud.kong.client.ConsumerClient;
import com.bocloud.kong.model.Consumer;
import com.bocloud.kong.service.ConsumerService;
import com.bocloud.model.Result;
import com.google.common.base.Preconditions;

/**
 * Title: ConsumerServiceImpl Description:
 *
 * @author lkx
 * @version 1.0.0
 * @since 2017-02-15 17:51
 */
@Service
public class ConsumerServiceImpl implements ConsumerService {

	private static Logger logger = LoggerFactory.getLogger(ConsumerServiceImpl.class);

	@Autowired
	private ConsumerClient consumerClient;

	@Override
	public Consumer query(String consumerId) {
		try {
			Consumer consumer = consumerClient.queryOne(consumerId);
			logger.debug("Consumer 信息 {}", JSON.toJSONString(consumer));
			return consumer;
		} catch (IOException e) {
			logger.warn("{}", e);
		}
		return null;
	}

	@Override
	public Result save(Consumer consumer) {
		Preconditions.checkNotNull(consumer, "待保存的开发者信息不能为空");
		try {
			Consumer newConsumer;
			if (isBlank(consumer.getId())) {
				newConsumer = consumerClient.add(consumer);
			} else {
				newConsumer = consumerClient.update(consumer);
			}
			if (newConsumer != null && isBlank(newConsumer.getErrorMessage())) {
				return new Result(true, "保存开发者信息成功");
			}
			return new Result(false, newConsumer == null ? "保存失败" : newConsumer.getErrorMessage());
		} catch (IOException e) {
			logger.info("{}", e);
			return new Result(false, e.getMessage());
		}
	}

	@Override
	public List<Consumer> queryAll(Consumer consumer) {
		try {
			Consumer queryParam = consumer == null ? new Consumer() : consumer;
			queryParam.setSize(getConsumerAmount());
			return consumerClient.query(queryParam);
		} catch (IOException e) {
			logger.info("{}", e);
		}
		return null;
	}

	@Override
	public void delete(String consumerId) {
		try {
			consumerClient.delete(consumerId);
		} catch (IOException e) {
			logger.info("{}", e);
		}
	}

	private Integer getConsumerAmount() {
		try {
			Consumer c = new Consumer();
			c.setSize(1);
			return consumerClient.totalSize(c);
		} catch (IOException e) {
			logger.info("{}", e);
		}
		return null;
	}
}
